package experiment.e07.code;

import java.io.*;

/**
 * @author thinkpad - 83start
 * @version v1.0
 * @create 2022/11/10 14:12
 * @package experiment.e07
 * @description 选择一个含有中文注释的.java文件，使用FileInputStream和FileReader分别读取文件，
 * 并把内容显示在控制台上。然后使用FileOutputStream和FileWriter将文件分别将文件复制到另一个文件
 * copyfile1.txt和 copyfile2.txt中，文件的保存位置自己确定。
 */

public class Ch02 {
    public static void main(String[] args) throws IOException {
        // 文件路径
        final String PATH = "./src/experiment/e07/code/file/BinarySearchNonRecursive.java";
        final String OBJ_PATH_1 = "./src/experiment/e07/code/file/copyfile1.txt";
        final String OBJ_PATH_2 = "./src/experiment/e07/code/file/copyfile2.txt";

        // FileInputStream 测试
        FileInputStreamTest fileInputStreamTest = new FileInputStreamTest();
        fileInputStreamTest.readAndShow(PATH);
        fileInputStreamTest.copyFile(PATH, OBJ_PATH_1);

        // FileReader 测试
        FileReaderTest fileReaderTest = new FileReaderTest();
        fileReaderTest.readAndShow(PATH);
        fileReaderTest.copyFile(PATH, OBJ_PATH_2);
    }
}

class FileInputStreamTest {
    /**
     * 读取文件并显示在控制台上
     *
     * @param path 目标文件的路径
     * @throws IOException
     */
    public void readAndShow(String path) throws IOException {
        FileInputStream fis = new FileInputStream(path);
        FileOutputStream fos = new FileOutputStream(FileDescriptor.out);
        int ch;
        while ((ch = fis.read()) != -1) {
            fos.write(ch);
        }

        fis.close();
        fos.close();
    }

    /**
     * 拷贝文件
     *
     * @param path1 读取文件的路径
     * @param path2 拷贝文件的路径
     * @throws IOException
     */
    public void copyFile(String path1, String path2) throws IOException {
        File file1 = new File(path1);
        File file2 = new File(path2);

        int ch;

        FileInputStream fis = new FileInputStream(file1);
        FileOutputStream fos = new FileOutputStream(file2);

        while ((ch = fis.read()) != -1) {
            fos.write(ch);
        }

        fis.close();
        fos.close();

    }
}

class FileReaderTest {
    /**
     * 读取文件并显示在控制台上
     *
     * @param path 读取文件的路径
     * @throws IOException
     */
    public void readAndShow(String path) throws IOException {
        FileReader fr = new FileReader(path);
        FileWriter fw = new FileWriter(FileDescriptor.out);
        int ch;
        while ((ch = fr.read()) != -1) {
            fw.write(ch);
        }

        fr.close();
        fw.close();
    }

    /**
     * 拷贝文件
     *
     * @param path1 读取文件的路径
     * @param path2 拷贝文件的路径
     * @throws IOException
     */
    public void copyFile(String path1, String path2) throws IOException {
        FileReader fr = new FileReader(new File(path1));
        FileWriter fw = new FileWriter(new File(path2));

        int ch;
        while ((ch = fr.read()) != -1) {
            fw.write(ch);
        }

        fr.close();
        fw.close();
    }
}
